package com.examstack.management.service;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;

import org.apache.poi.POIXMLDocument;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.examstack.common.domain.exam.AnswerSheet;
import com.examstack.common.domain.exam.AnswerSheetItem;
import com.examstack.common.domain.exam.Exam;
import com.examstack.common.domain.exam.ExamPaper;
import com.examstack.common.domain.exam.Paper;
import com.examstack.common.domain.question.QuestionContent;
import com.examstack.common.domain.question.QuestionQueryResult;
import com.examstack.common.domain.question.QuestionStatistic;
import com.examstack.common.domain.question.QuestionStruts;
import com.examstack.common.util.CustomXWPFDocument;
import com.examstack.common.util.ExamPaperExportUtil;
import com.examstack.common.util.Page;
import com.examstack.management.persistence.ExamMapper;
import com.examstack.management.persistence.ExamPaperMapper;
import com.examstack.management.persistence.QuestionMapper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

@Service("examPaperService")
public class ExamPaperServiceImpl implements ExamPaperService {

	@Autowired
	private ExamPaperMapper examPaperMapper;
	@Autowired
	private QuestionMapper questionMapper;
	@Autowired
	private QuestionService questionService;
	@Autowired
	private ExamMapper examMapper;

	@Override
	public List<ExamPaper> getExamPaperList(String searchStr, String paperType, Page<ExamPaper> page) {
		// TODO Auto-generated method stub
		return examPaperMapper.getExamPaperList(searchStr, paperType, page);
	}

	@Override
	public void insertExamPaper(ExamPaper examPaper) {
		// TODO Auto-generated method stub
		examPaperMapper.insertExamPaper(examPaper);
	}

	@Override
	@Transactional
	public void createExamPaper(HashMap<Integer, HashMap<Integer, List<QuestionStruts>>> questionMap,
			HashMap<Integer, Integer> questionTypeNum, HashMap<Integer, Float> questionTypePoint,
			HashMap<Integer, Float> knowledgePointRate, ExamPaper examPaper) {
		// TODO Auto-generated method stub

		HashMap<Integer,String> knowledgeMap = (HashMap<Integer, String>) questionService.getKnowledgePointMap(0);
		HashMap<Integer,String> typeMap = (HashMap<Integer, String>) questionService.getQuestionTypeMap();
		Paper paper = new Paper(questionMap, questionTypeNum, questionTypePoint, knowledgePointRate, knowledgeMap, typeMap);
		try {
			paper.createPaper();
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e1.getMessage());
		}

		try {
			HashMap<Integer, QuestionStruts> paperQuestionMap = paper.getPaperQuestionMap();

			Iterator<Integer> it = paperQuestionMap.keySet().iterator();
			//试卷题目 id list
			List<Integer> idList = new ArrayList<Integer>();
			while (it.hasNext()) {
				idList.add(it.next());
			}
			List<QuestionQueryResult> questionList = questionMapper.getQuestionAnalysisListByIdList(idList);
			for (QuestionQueryResult q : questionList) {
				q.setQuestionPoint(questionTypePoint.get(q.getQuestionTypeId()));
			}
			Gson gson = new Gson();
			examPaper.setContent(gson.toJson(questionList));
	
			examPaperMapper.insertExamPaper(examPaper);
			
			/**
			 * 更新试卷状态为 完成
			 */
			int sum = 0;
			AnswerSheet as = new AnswerSheet();
			as.setExamPaperId(examPaper.getId());
			List<AnswerSheetItem> asList = new ArrayList<AnswerSheetItem>();
			for(QuestionQueryResult q : questionList){
				AnswerSheetItem item = new AnswerSheetItem();
				item.setAnswer(q.getAnswer());
				item.setQuestionId(q.getQuestionId());
				item.setPoint(q.getQuestionPoint());
				item.setQuestionTypeId(q.getQuestionTypeId());
				sum += q.getQuestionPoint();
				asList.add(item);
			}
			as.setPointMax(sum);
			as.setAnswerSheetItems(asList);
			String answerSheet = gson.toJson(as);
			examPaper.setAnswer_sheet(answerSheet);
			examPaper.setTotal_point(sum);
			examPaperMapper.updateExamPaper(examPaper);
			
			/**
			 * 发布试卷为模拟考试
			 */
			
			
			
			
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage());
		}

	}

	@Override
	public ExamPaper getExamPaperById(int examPaperId) {
		// TODO Auto-generated method stub
		return examPaperMapper.getExamPaperById(examPaperId);
	}

	@Override
	public void updateExamPaper(ExamPaper examPaper) {
		// TODO Auto-generated method stub
		examPaperMapper.updateExamPaper(examPaper);
	}

	@Override
	public void deleteExamPaper(int id) {
		// TODO Auto-generated method stub
		/**删考试**/
		List<Exam> exams = examMapper.getExambyExampaperId(id);
		for(Exam exam :exams){
			examMapper.deleteExamById(exam.getExamId());
		}
		examPaperMapper.deleteExamPaper(id);
	}

	@Override
	public List<ExamPaper> getEnabledExamPaperList(String userName, Page<ExamPaper> page) {
		// TODO Auto-generated method stub
		return examPaperMapper.getEnabledExamPaperList(userName, page);
	}

	@SuppressWarnings("unused")
	@Override
	public void generateDoc(ExamPaper examPaper, String path) throws Exception {
		// TODO Auto-generated method stub
		String basePath = System.getProperty("catalina.base") + ",webapps,";
		String filePath = basePath + "Management,resources,template,doc_tmp.docx";
		filePath = filePath.replace(',', File.separatorChar);
		OPCPackage pack = POIXMLDocument.openPackage(filePath);
		CustomXWPFDocument doc = new CustomXWPFDocument(pack);
		Gson gson = new Gson();
		String content = examPaper.getContent();
		List<QuestionQueryResult> questionList = gson.fromJson(content, new TypeToken<List<QuestionQueryResult>>(){}.getType());
		
		String [] qids = new String[questionList.size()];
		int i = 0;
		for(QuestionQueryResult qr : questionList){
			qids[i] = qr.getQuestionId()+"";
			i++;
		}
		/***试题类型数***/
		List<QuestionStatistic> questionTypes = questionMapper.getTypeQuestionStaticByFieldIdAndQids(examPaper.getField_id(),qids);		
		/**设置标题**/
		ExamPaperExportUtil.setTilte(doc, examPaper.getName());
		ExamPaperExportUtil.setOtherLine(doc);
		/**设置副标题**/
		String bj1 = "注意事项:  1 答卷前将装订线左边的项目填写清楚。";
		String bj2 = "          2 答卷必须用蓝色或黑色钢笔、圆珠笔，不许用铅笔或红笔。";
		String bj3 = "          3 本试卷满分"+examPaper.getTotal_point()+"分，考试时间"+examPaper.getDuration()+"分钟。";
		ExamPaperExportUtil.setBJ(doc, bj1);
		ExamPaperExportUtil.setBJ(doc, bj2);
		ExamPaperExportUtil.setBJ(doc, bj3);
		ExamPaperExportUtil.setOtherLine(doc);
		/**表格**/
		Map<Integer,List<String>> cellNames = new HashMap<>();
		String[] cells1 = {"题型", "填空题", "单选题", "简答题","合计",  "阅卷人"};
		String[] cells2 = {"得分",  "",    "",     "",    "",     ""};
		cellNames.put(0, Arrays.asList(cells1));
		cellNames.put(1, Arrays.asList(cells2));
		ExamPaperExportUtil.setTable(doc, 2, 6, cellNames);
		ExamPaperExportUtil.setOtherLine(doc);
		String[] questionTypesIndex = {"一、", "二、", "三、", "四、", "五、", "六、", "七、", "八、", "九、"};
		
		for (int j = 0; j < questionTypes.size(); j++) {
			String qGName =questionTypesIndex[j]+questionTypes.get(j).getQuestionTypeName()+"（共"+questionTypes.get(j).getAmount()+"题，";
			int total = questionTypes.get(j).getAmount();
			int qindex = 1;
			for (QuestionQueryResult question : questionList) {

				if (questionTypes.get(j).getQuestionTypeId() == question.getQuestionTypeId()) {
					QuestionContent questionContent = gson.fromJson(question.getContent(), QuestionContent.class);
					if(qindex == 1){
						qGName += "每题"+question.getQuestionPoint()+"分，共"+(question.getQuestionPoint()*total)+"分)";
						ExamPaperExportUtil.setQuestionGroup(doc, qGName);
					}
					// 设置试题标题
				/*	XWPFParagraph t = doc.createParagraph();
					// 设置字体对齐方式
					t.setAlignment(ParagraphAlignment.LEFT);
					t.setVerticalAlignment(TextAlignment.TOP);
					XWPFRun rt = t.createRun();
					// 设置字体是否加粗
					rt.setBold(false);
					rt.setFontSize(15);
					// 设置使用何种字体。
					rt.setFontFamily("Courier");
					// 设置上下两行之间的间距
					rt.setTextPosition(40);
					rt.setText(qindex + "." + questionContent.getTitle() + "(" + question.getQuestionPoint() + "分)");*/
					String qName = qindex + "." + questionContent.getTitle() + "(" + question.getQuestionPoint() + "分)";
					ExamPaperExportUtil.setQuestion(doc, qName);
					
					if (!"".equals(questionContent.getTitleImg()) && questionContent.getTitleImg() != null) {
						String titlePicPath = basePath.replace(',', File.separatorChar);
						File titlePic = new File(titlePicPath + questionContent.getTitleImg());

						BufferedImage sourceImg = ImageIO.read(new FileInputStream(titlePic));

						String ind = doc.addPictureData(new FileInputStream(titlePic), XWPFDocument.PICTURE_TYPE_JPEG);
						doc.createPicture(doc.getAllPictures().size() - 1, sourceImg.getWidth() / 2,
								sourceImg.getHeight() / 2);
						sourceImg.flush();
					}
					ExamPaperExportUtil.setOtherLine(doc);
					//选择题和判断题增加选项（增加识绘图）
					if ((question.getQuestionTypeId() == 1 || question.getQuestionTypeId() == 2
							|| question.getQuestionTypeId() == 3 || question.getQuestionTypeId() == 8)
							&& questionContent.getChoiceList()!= null) {
						for (Map.Entry<String, String> entry : questionContent.getChoiceList().entrySet()) {
						/*	// 设置试题标题
							XWPFParagraph c = doc.createParagraph();
							// 设置字体对齐方式
							c.setAlignment(ParagraphAlignment.LEFT);
							c.setVerticalAlignment(TextAlignment.TOP);

							XWPFRun rc = c.createRun();
							// 设置字体是否加粗
							rc.setBold(false);
							rc.setFontSize(15);
							// 设置使用何种字体
							rc.setFontFamily("Courier");
							// 设置上下两行之间的间距
							rc.setTextPosition(40);
							rc.setText(entry.getKey() + " " + entry.getValue());*/
							ExamPaperExportUtil.setQuestion(doc, entry.getKey() + " " + entry.getValue());

							if (questionContent.getChoiceImgList() != null && 
									questionContent.getChoiceImgList().containsKey(entry.getKey())) {
								String picPath = basePath.replace(',', File.separatorChar)
										+ questionContent.getChoiceImgList().get(entry.getKey());
								System.out.println(picPath);
								File picture = new File(picPath);
								BufferedImage sourceImg = ImageIO.read(new FileInputStream(picture));

								String ind = doc.addPictureData(new FileInputStream(picture),
										XWPFDocument.PICTURE_TYPE_JPEG);
								doc.createPicture(doc.getAllPictures().size() - 1, sourceImg.getWidth() / 2,
										sourceImg.getHeight() / 2);
								sourceImg.flush();
							}
							ExamPaperExportUtil.setOtherLine(doc);
						}
					}
					qindex++;
				}
			} 
		}
		FileOutputStream out;
		try {
			File f = new File(path);
			if(!f.exists())
				f.mkdirs();
			
			out = new FileOutputStream(path + File.separatorChar + examPaper.getName() + ".docx");
			doc.write(out);
			out.close();
			System.out.println("success");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
